package com.unipay.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unipay.cmn.lintener.DictListener;
import com.unipay.cmn.mapper.DictMapper;
import com.unipay.cmn.service.DictService;
import com.unipay.model.cmn.Dict;
import com.unipay.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-04-01 21:21:21
 * @Desc: TODO
 */
@Service
@Transactional
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //TODO 文件，上传（创建：回调监听器）
    //文件参数：MultipartFile file
    @Override
    public void importData(MultipartFile file) {
        try {
            //回调监听器：实例化时候传参 mapper，供内部查询方法，一条一条插入数据库
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("上传!");
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictcode, String value) {
        //判断：如果dictcode为空，直接根据value查询
        if (StringUtils.isEmpty(dictcode)) {
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(dictQueryWrapper);
            return dict.getName();
        } else {
            //TODO （1）根据dictcode查询dict对象，得到dict的id值
            Dict dictByDictCode = this.getDictByDictCode(dictcode);
            //TODO （2）根据parent_id和value进行查询
            Long parent_id = dictByDictCode.getId();
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id", parent_id);
            dictQueryWrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(dictQueryWrapper);
            return dict.getName();
        }
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取对应id
        Dict dictByDictCode = this.getDictByDictCode(dictCode);
        //根据id获取子节点
        List<Dict> childData = this.findChildData(dictByDictCode.getId());
        return childData;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        return dict;
    }


    //TODO excel下载
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //（1）设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("dict", "utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //（2）查询数据
            List<Dict> dictList = baseMapper.selectList(null);
            // Dict -> DictVo
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                // ---工具类---
                BeanUtils.copyProperties(dict, dictEeVo, DictEeVo.class);
                dictVoList.add(dictEeVo);
            }
            //（3）调用方法，导出
            //ServletOutputStream servletOutputStream = response.getOutputStream();
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("导出！");
        }
    }

    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        //向list集合中，每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean hasChildren = this.setHasChildren(dictId);
            dict.setHasChildren(hasChildren);
        }
        return dictList;
    }

    //dict对象中设置hasChildren
    private boolean setHasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
